package com.hifar.test.syncData.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.common.QueryParamBean;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.model.VO.IdVO;
import com.hifar.model.VO.QueryParamsVO;
import com.hifar.plat.flowvar.service.IFlowPriVarService;
import com.hifar.sys.MinioUtil;
import com.hifar.test.syncData.pojo.HfEnvSyncDataExportTableInfo;
import com.hifar.test.syncData.pojo.HfEnvSyncDataExportTask;
import com.hifar.test.syncData.pojo.VO.SyncDataExportTaskDetailVO;
import com.hifar.test.syncData.service.IHfEnvSyncDataExportTableInfoService;
import com.hifar.test.syncData.service.IHfEnvSyncDataExportTaskService;
import com.hifar.sys.BusiResponse;
import com.hifar.sys.PageResult;
import com.hifar.sys.SystemUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author zhuWeiWei
 * @description 数据同步导出记录
 * @date 2025/4/11 17:30
 */
@Api("数据同步导出记录")
@RestController
@RequestMapping("/api/busi/test/syncExportTask")
@Slf4j
public class HfEnvSyncDataExportTaskController {

    @Autowired
    private IHfEnvSyncDataExportTaskService syncDataExportTaskService;

    @Autowired
    private IHfEnvSyncDataExportTableInfoService exportTableInfoService;


    @ApiOperation("分页列表查询")
    @PostMapping("/listPage")
    public BusiResponse listPage(@RequestBody QueryParamsVO queryParamsVO) {
        QueryParamBean<HfEnvSyncDataExportTask> queryParamBean = new QueryParamBean<>(queryParamsVO);
        queryParamBean.addColumns(HfEnvSyncDataExportTask.class);
        QueryWrapper<HfEnvSyncDataExportTask> queryWrapper = queryParamBean.getQueryWrapper();
        Page<HfEnvSyncDataExportTask> page = queryParamBean.getPage();
        queryWrapper.orderByDesc("create_time");
        Page<HfEnvSyncDataExportTask> pageData = syncDataExportTaskService.page(page, queryWrapper);
        List<HfEnvSyncDataExportTask> records = pageData.getRecords();
        for (HfEnvSyncDataExportTask record : records) {
            String filePath = record.getFilePath();
            String bucketPre = record.getBucketPre();
            Integer secretLevel = record.getSecretLevel();

            if (StringUtils.isNotBlank(filePath)) {
                String downloadFilePath = MinioUtil.getFullFilePaths(bucketPre, filePath, secretLevel);
                record.setFilePath(downloadFilePath);
            }
        }


        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }

    @ApiOperation("查询导出任务详情")
    @PostMapping("/detail")
    public BusiResponse detail(@RequestBody @Validated IdVO idVO) {
        String taskId = idVO.getId();
        if (StringUtils.isBlank(taskId)) {
            return BusiResponse.error("任务ID不能为空");
        }

        // 查询任务基本信息
        HfEnvSyncDataExportTask exportTask = syncDataExportTaskService.getById(taskId);
        if (exportTask == null) {
            return BusiResponse.error("导出任务不存在");
        }

        // 封装详情VO
        SyncDataExportTaskDetailVO detailVO = new SyncDataExportTaskDetailVO();
        BeanUtils.copyProperties(exportTask, detailVO);

        // 查询表导出详情列表
        QueryWrapper<HfEnvSyncDataExportTableInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_id", taskId);
        queryWrapper.orderByAsc("create_time");
        List<HfEnvSyncDataExportTableInfo> tableInfoList = exportTableInfoService.list(queryWrapper);

        log.info("查询导出任务详情，taskId: {}, 查询到 {} 条表记录", taskId, tableInfoList != null ? tableInfoList.size() : 0);
        if (tableInfoList != null && !tableInfoList.isEmpty()) {
            log.debug("表记录详情: {}", tableInfoList);
        }

        detailVO.setTableInfoList(tableInfoList);

        // 计算总记录数量、表数量和附件统计
        int totalRecordNum = 0;
        int actualTableCount = 0;
        int successTableCount = 0;
        int failTableCount = 0;
        int totalFileCount = 0;
        int successFileCount = 0;
        int failFileCount = 0;

        if (tableInfoList != null) {
            actualTableCount = tableInfoList.size();
            for (HfEnvSyncDataExportTableInfo tableInfo : tableInfoList) {
                // 记录数统计
                if (tableInfo.getRecordNum() != null) {
                    totalRecordNum += tableInfo.getRecordNum();
                }
                
                // 表状态统计
                if ("1".equals(tableInfo.getStatus())) {
                    successTableCount++;
                } else {
                    failTableCount++;
                }
                
                // 附件统计
                if (tableInfo.getFileTotal() != null) {
                    totalFileCount += tableInfo.getFileTotal();
                }
                if (tableInfo.getFileSuccess() != null) {
                    successFileCount += tableInfo.getFileSuccess();
                }
                if (tableInfo.getFileFail() != null) {
                    failFileCount += tableInfo.getFileFail();
                }
            }
        }

        // 使用实际导出的表数量，而不是taskCount字段
        detailVO.setTaskCount(actualTableCount);
        detailVO.setTotalRecordNum(totalRecordNum);
        detailVO.setSuccessTableCount(successTableCount);
        detailVO.setFailTableCount(failTableCount);
        detailVO.setTotalFileCount(totalFileCount);
        detailVO.setSuccessFileCount(successFileCount);
        detailVO.setFailFileCount(failFileCount);

        log.info("统计结果 - 表数量: {}, 总记录数: {}, 成功: {}, 失败: {}, 附件: {}/{}/{}",
                actualTableCount, totalRecordNum, successTableCount, failTableCount, 
                successFileCount, failFileCount, totalFileCount);

        return BusiResponse.OK(detailVO);
    }
}
